package com.lagou.rpc.consumer.conf;

import com.lagou.rpc.api.IUserService;
import com.lagou.rpc.consumer.bean.ServiceProvider;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

import java.util.List;

@Configuration
@ConfigurationProperties(prefix = "rpc")
public class RpcConfig implements InitializingBean {

    @Getter
    @Setter
    private List<ServiceProvider> serviceProviders;

    private RpcClientProxy rpcClientProxy;

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(serviceProviders, "no service provider!");
        // 初始化RPC代理，注册服务
        rpcClientProxy = new RpcClientProxy();
        for (ServiceProvider serviceProvider : serviceProviders) {
            rpcClientProxy.registerServiceProvider(serviceProvider);
        }
    }

    @Bean
    public IUserService getUserService() {
        return (IUserService) rpcClientProxy.createProxy(IUserService.class);
    }

}
